package com.ciaojian.client.controller;

import com.ciaojian.client.service.CouponServiceImpl;
import com.ciaojian.client.service.SettingServiceImpl;
import com.ciaojian.core.enums.sys.SysSettingEnum;
import com.ciaojian.core.factory.ObjectMapperFactory;
import com.ciaojian.core.util.LogUtil;
import com.ciaojian.core.util.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author Atlakyn
 */
@Api(tags = "系统设置")
@RestController
@RequestMapping
public class SettingController {
    @Resource
    private SettingServiceImpl settingService;
    @Resource
    private CouponServiceImpl couponService;

    @ApiOperation("分享设置")
    @GetMapping("/share-setting")
    public Result getShareSetting() {
        String value = settingService.getBaseMapper().getValue(SysSettingEnum.SHARE_SETTING.getName());
        ObjectMapper om = ObjectMapperFactory.getObjectMapperInstance();
        try {
            // 把 Json 字符串转成 JsonNode 对象,以便后续操作
            JsonNode jsonNode = om.readTree(value);
            // 获取到 "share" 节点
            JsonNode share = jsonNode.get("share");
            // 遍历节点
            share.forEach(i -> {
                ObjectNode on = (ObjectNode) i;
                // 根据 CouponId 拿到 Coupon 对象
                JsonNode jn = om.valueToTree(couponService.getById(i.get("sharedCoupon").asInt()));
                // 把 Coupon 对象信息存入原来的节点中
                on.set("sharedCoupon", jn);
            });
            return Result.ok(jsonNode);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            LogUtil.writeErrorLog(String.format("share-setting 接口Json转换异常,Json字符串:%s", value));
            return Result.error("Json 转换异常");
        }
    }

}
